import React, { useEffect, useState } from 'react'
import ArticleItem from '../../components/Article/ArticleItem'
import Title from '../../components/Title/Title'
import Pagination from '../../components/Pagination/Pagination'
import Banner from '../../components/Banner/Banner'
import axios from '../../axios'
import AboutMe from '../../components/AboutMe/AboutMe'
import './index.scss'

export default function Home() {
  const [articleList, setArticleList] = useState([])
  const [pageSize] = useState(10)
  const [pageIndex, setPageIndex] = useState(1)
  const [total, setTotal] = useState(0)

  useEffect(() => {
    axios.get('/article', {
      pageIndex,
      pageSize
    }).then(res => {
      console.log(res)
      setArticleList(res.data.records)
      setTotal(res.data.total)
      // 不是第一页自动滚动
      if(pageIndex > 1) {
        window.scrollTo({
          left: 0,
          top: 570,
          behavior: 'smooth'
        })
      }
    })
  }, [pageIndex, pageSize])
  
  const changePageIndex = (index) => {
    setPageIndex(index)
  }

  // const showList = useMemo(() => {
  //   return articleList.slice((pageIndex - 1) * pageSize, pageSize * pageIndex)
  // }, [articleList, pageSize, pageIndex])


  return (
    <div className='home'>
      <div style={{display: 'flex'}}>
        <Banner></Banner>
        <AboutMe style={{flex: 1}}></AboutMe>
      </div>
      <Title>最新文章</Title>
      <div className='list'>
        {
          articleList.map(item => {
            return (
              <ArticleItem key={item._id} {...item}></ArticleItem>
            )
          })
        }
      </div>
      <Pagination current={pageIndex} pageSize={pageSize} total={total} change={changePageIndex}></Pagination>
    </div>
  )
}
